package com.yanqu.road.server.manger.config;

import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eTradeWarBattleType;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.tradewar.UserTradeWarRecord;
import com.yanqu.road.logic.bussiness.config.TradeWarBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.tradewar.TradeWarBuilding;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.activity.curio.CurioMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TradeWarConfigMgr extends TempMgr {

	private static Logger logger = LogManager.getLogger(TradeWarConfigMgr.class.getName());

	private static Map<Integer, Map<Integer, TradeWarBuilding>> tradeWarBuildingMap;

	private static RandomHelper threadRandom = new RandomHelper();

	@Override
	public boolean init() throws Exception {
		return reload();
	}

	@Override
	public boolean stop() {
		return false;
	}

	@Override
	public boolean save() {
		return false;
	}

	@Override
	public boolean reloadConfig() {
		tradeWarBuildingMap = TradeWarBussiness.getTradeWarBuildingMap();
		if (tradeWarBuildingMap.size() <= 0) {
			return false;
		}
		return true;
	}

	@Override
	public boolean reloadData() throws Exception {
		return true;
	}

	/**
	 * 商战鼓舞消耗
	 */
	public static BigInteger getTradeWarBuffCost(BigInteger earnSpeed, int times) {
		BigDecimal temp1 = new BigDecimal(earnSpeed);
		BigDecimal temp2 = BigDecimal.valueOf(((double)times * ConfigMgr.getTradeWarBuyBuffCostParam1() + ConfigMgr.getTradeWarBuyBuffCostParam2()) / 1000).setScale(10, BigDecimal.ROUND_UP);
		return temp1.multiply(temp2).setScale(0, BigDecimal.ROUND_UP).toBigInteger();
	}

	/**
	 * 跨服商战鼓舞消耗
	 */
	public static BigInteger getCrossTradeWarBuffCost(BigInteger earnSpeed, int times) {
		BigDecimal temp1 = new BigDecimal(earnSpeed);
		BigDecimal temp2 = BigDecimal.valueOf(((double)times * ConfigMgr.getCrossTradeWarBuyBuffCostParam1() + ConfigMgr.getCrossTradeWarBuyBuffCostParam2()) / 1000).setScale(10, BigDecimal.ROUND_UP);
		return temp1.multiply(temp2).setScale(0, BigDecimal.ROUND_UP).toBigInteger();
	}

	/**
	 * 商战税所奖励
	 */
	public static int getBankExpReward(int killPatronsCount, int userItemId){
		double reward = Math.round(threadRandom.nextDouble((double) killPatronsCount * ConfigMgr.getTradeWarRewardParam2() / 1000,
				(double) killPatronsCount * ConfigMgr.getTradeWarRewardParam3() / 1000));
		if(userItemId > 0){
			GoodsInfo goodsInfo = GoodsMgr.getGoodsById(userItemId);
			if(null != goodsInfo){
				reward = reward * goodsInfo.getParamList().get(2).intValue() / 1000;
			}
		}
		return (int)reward;
	}

	/**
	 * 跨服商战税所奖励
	 */
	public static int getCrossBankExpReward(int killPatronsCount, int userItemId){
		double reward =  Math.round(threadRandom.nextDouble((double) killPatronsCount * ConfigMgr.getCrossTradeWarRewardParam2() / 1000,
				(double) killPatronsCount * ConfigMgr.getCrossTradeWarRewardParam3() / 1000));
		if(userItemId > 0){
			GoodsInfo goodsInfo = GoodsMgr.getGoodsById(userItemId);
			if(null != goodsInfo){
				reward = reward * goodsInfo.getParamList().get(2).intValue() / 1000;
			}
		}
		return (int)reward;
	}

	/**
	 * 商战币奖励
	 */
	public static int getTradeWarScoreReward(GamePlayer player, int killPatronsCount, int userItemId){
		double skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.TradeWarScoreItem.getValue(), 0);
//		logger.info("userId:{},getTradeWarScoreReward skillAddition:{}", player.getUserId(), skillAddition);
		int value1 = killPatronsCount * 2;
		int value2 = Math.max(0, killPatronsCount - 5);
		int value3 = Math.max(0, killPatronsCount - 15);
		int value4 = Math.max(0, killPatronsCount - 25);
		int value5 = Math.max(0, killPatronsCount - 35);
		double value6 = (double) ConfigMgr.getTradeWarRewardParam1() / 1000;
		double score = value6 * (value1 + value2 + value3 + value4 + value5);
//		logger.info("userId:{},getTradeWarScoreReward score:{}", player.getUserId(), score);
		score = score * (skillAddition / 1000 + 1);
//		logger.info("userId:{},getTradeWarScoreReward addition score:{}", player.getUserId(), score);
		if(userItemId > 0){
			GoodsInfo goodsInfo = GoodsMgr.getGoodsById(userItemId);
			if(null != goodsInfo){
				score = score * goodsInfo.getParamList().get(2).intValue() / 1000;
			}
		}
		return (int)Math.ceil(score);
	}

	/**
	 * 跨服商战荣誉币奖励
	 */
	public static int getCrossTradeWarScoreReward(GamePlayer player, int killPatronsCount, int useItemId){
		int skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.TradeWarScoreItem.getValue(), 0);
		return getCrossTradeWarScoreReward(skillAddition, killPatronsCount, useItemId);
	}

	/**
	 * 跨服商战荣誉币奖励
	 */
	public static int getCrossTradeWarScoreReward(int skillAddition, int killPatronsCount, int useItemId){
		int value1 = killPatronsCount * 2;
		int value2 = Math.max(0, killPatronsCount - 5);
		int value3 = Math.max(0, killPatronsCount - 15);
		int value4 = Math.max(0, killPatronsCount - 25);
		int value5 = Math.max(0, killPatronsCount - 35);
		double value6 = (double) ConfigMgr.getCrossTradeWarRewardParam1() / 1000;
		double score = value6 * (value1 + value2 + value3 + value4 + value5);
		score = score * ((double) skillAddition / 1000 + 1);
		if(useItemId > 0){
			GoodsInfo goodsInfo = GoodsMgr.getGoodsById(useItemId);
			if(null != goodsInfo){
				score = score * goodsInfo.getParamList().get(2).intValue() / 1000;
			}
		}
		return (int)Math.ceil(score);
	}

	/**
	 * 商战鼓舞加成
	 */
	public static int getTradeWarBuffAddition(int buyBuffTimes){
		return GameConfig.TRADE_WAR_BUFF_ADDITION * buyBuffTimes;
	}

	/**
	 * 商战鼓舞加成
	 */
	public static int getCrossTradeWarBuffAddition(int buyBuffTimes){
		return GameConfig.CROSS_TRADE_WAR_BUFF_ADDITION * buyBuffTimes;
	}

	public static TradeWarBuilding getTradeWarBuilding(int type, int level){
		if(tradeWarBuildingMap.containsKey(type)){
			return tradeWarBuildingMap.get(type).get(level);
		}
		return null;
	}

	/**
	 *门客买挑战次数元宝消耗
	 */
	public static int getPatronsBuyBattleTimesCost(int buyTimes){
		return GameConfig.TRADE_WAR_PATRONS_BUY_TIMES_BASE_INGOTS + GameConfig.TRADE_WAR_PATRONS_BUY_TIMES_ADD_INGOTS * buyTimes;
	}

	/**
	 *门客最多挑战次数，门客默认挑战次数加最多购买次数
	 */
	public static int getPatronsMaxBattleTimes(){
		return GameConfig.TRADE_WAR_PATRONS_DEFAULT_BATTLE_TIMES + GameConfig.TRADE_WAR_MAX_PATRONS_BUY_TIMES;
	}

	/**
	 *跨服商战门客最多挑战次数
	 */
	public static int getCrossPatronsMaxBattleTimes(){
		return GameConfig.CROSS_TRADE_WAR_PATRONS_DEFAULT_BATTLE_TIMES;
	}

	/**
	 * 打乱对面门客出手顺序
	 */
	public static List<UserPatrons> disorganizeOrder(List<UserPatrons> patronsList) {
		List<UserPatrons> dataList = new ArrayList<>();
		List<UserPatrons> tempList = new ArrayList<>(patronsList);
		for (; tempList.size() > 0; ) {
			int index = threadRandom.next(0, tempList.size());
			dataList.add(tempList.get(index));
			tempList.remove(tempList.get(index));
		}
		return dataList;
	}

	/**
	 * 商战加分数技能加成
	 */
	public static int getAddTradeWarScoreSkillAddition(GamePlayer player, List<Integer> patronsIdList){
		int skillAddition = player.getModule(PatronsModule.class).getTalentTradeWarScoreSkillAddition(eSkillType.TradeWarAddMyScore.getValue(), patronsIdList);
		skillAddition += player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.TradeWarAddScore.getValue(), 0);
		skillAddition += CurioMgr.getSkillAdditionBySkillType(eSkillType.CurioTradeWarSelfAddSkill.getValue(), player, 0);
		return skillAddition;
	}

	/**
	 * 商战减分数技能加成
	 */
	public static int getLoseTradeWarScoreSkillAddition(GamePlayer player, List<Integer> patronsIdList){
		int skillAddition = player.getModule(PatronsModule.class).getTalentTradeWarScoreSkillAddition(eSkillType.TradeWarEnemyLoseScore.getValue(), patronsIdList);
		skillAddition += CurioMgr.getSkillAdditionBySkillType(eSkillType.CurioTradeWarOpponentAddSkill.getValue(), player, 0);
		return skillAddition;
	}

	/**
	 * 商战扣分减少损失
	 * @param userPatronsList
	 * @return
	 */
	public static long getLoseTradeWarScoreSkillReduce(List<UserPatrons> userPatronsList) {
		long skillReduce = 0L;
		for (UserPatrons userPatrons : userPatronsList) {
			skillReduce += userPatrons.getTradeWarLoseScoreReduce();
		}
		return skillReduce;
	}

	/**
	 * 以自身为镜像，复制一份低实力的门客
	 */
	public static List<UserPatrons> initNpcPatronList(List<UserPatrons> patronsList){
		List<UserPatrons> disorganizeList = new ArrayList<>(patronsList);
		disorganizeList = TradeWarConfigMgr.disorganizeOrder(disorganizeList);
		List<UserPatrons> cloneList = new ArrayList<>();
		int patronsCount = patronsList.size();
		if(patronsCount >= GameConfig.TRADE_WAR_NOTICE_NEED_KILL_PATRONS_COUNT){
			patronsCount = GameConfig.TRADE_WAR_NOTICE_NEED_KILL_PATRONS_COUNT - 1;
		}
		for(UserPatrons userPatrons : disorganizeList){
			UserPatrons clonePatrons = userPatrons.cloneUserPatrons();
			clonePatrons.setLevel(clonePatrons.getLevel() / 2);
			if(clonePatrons.getLevel() <= 0){
				clonePatrons.setLevel(1);
			}
			clonePatrons.setStageLv(clonePatrons.getStageLv() / 2);
			if(clonePatrons.getStageLv() <= 0){
				clonePatrons.setStageLv(0);
			}
			clonePatrons.setQualification(clonePatrons.getQualification() / 2);
			clonePatrons.setAbility(clonePatrons.getAbility().divide(BigInteger.valueOf(2)));
			cloneList.add(clonePatrons);
			if(cloneList.size() >= patronsCount){
				break;
			}
		}
		return cloneList;
	}

	/**
	 * 是否今日的对手，只有挑战才是
	 */
	public static boolean isTodayEnemyRecord(long nowTime, UserTradeWarRecord record){
		return DateHelper.isSameDay(nowTime, record.getRecordTime()) && (record.getBattleType() != eTradeWarBattleType.FightBack.getValue()) &&
				(record.getBattleType() != eTradeWarBattleType.RandomBattle.getValue());
	}
	public static boolean isTodayEnemyRecord(UserTradeWarRecord record){
		long nowTime = System.currentTimeMillis() / 1000;
		return isTodayEnemyRecord(nowTime, record);
	}

	/**
	 * 跨服商战恢复出战的次数
	 */
	public static int getMaxCrossRestoreRandomBattleTimes(boolean isDefault){
		if(isDefault){
			return GameConfig.CROSS_TRADE_WAR_PATRONS_DEFAULT_RANDOM_BATTLE_TIMES;
		}else {
			return GameConfig.CROSS_TRADE_WAR_PATRONS_RESTORE_RANDOM_BATTLE_TIMES;
		}
	}

	/**
	 * 加商战币技能加成
	 */
	public static int getAddTradeWarScoreItemSkillAddition(GamePlayer player){
		int skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.TradeWarScoreItem.getValue(), 0);
		return skillAddition;
	}

	/**
	 * 是否跨服追缉变更
	 * @param trackChangeType
	 * @return
	 */
	public static boolean isCrossTrackChange(int trackChangeType){
		return trackChangeType == eTradeWarBattleType.Challenge.getValue();
	}

	/**
	 * 获取商战队伍快速出战鼓舞次数
	 * @param buyBuffTimeType
	 * @return
	 */
	public static int getTeamBuyBuffTimes(int buyBuffTimeType){
		if(1 == buyBuffTimeType){
			return GameConfig.TRADE_WAR_TEAM_BUY_BUFF_TIMES;
		}
		return 0;
	}
}
